package auth

import (
	"context"
	"goAdminV1/api/auth/v1"
	"goAdminV1/internal/model"
	"goAdminV1/utility"
)

func (c *ControllerV1) Login(ctx context.Context, req *v1.LoginReq) (res *v1.LoginRes, err error) {
	// 查询用户信息
	userInfo, err := model.GetUserByUsername(ctx, req.Email)
	if err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}

	if userInfo == nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}

	// 生成 token
	token, err := utility.GenerateToken(userInfo.Id, userInfo.Username)
	if err != nil {
		return nil, utility.Error(utility.CodeOperation, err)
	}

	// 返回自定义结构体
	return &v1.LoginRes{
		Token: token,
	}, nil
}
